package me.bincker.formwork.web.utils

import com.fasterxml.jackson.databind.ObjectMapper
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.web.context.request.RequestContextHolder
import org.springframework.web.context.request.ServletRequestAttributes
import java.util.*
import javax.servlet.http.HttpServletResponse

/**
 * 响应工具
 */
object ResponseUtils {
    private var objectMapper: ObjectMapper = SpringUtils.getBean(ObjectMapper::class.java)

    /**
     * 获取当前线程的Response
     */
    fun getResponse() = (RequestContextHolder.currentRequestAttributes() as ServletRequestAttributes).response ?: throw RuntimeException("无法通过RequestContextHolder对象获取Response")

    /**
     * 发送数据
     */
    fun send(obj: Any, response: HttpServletResponse = getResponse()){
        response.contentType = MediaType.APPLICATION_JSON_UTF8_VALUE
        objectMapper.writeValue(response.writer, obj)
    }

    /**
     * 发送错误
     */
    fun sendError(message: String = "操作失败", status: HttpStatus = HttpStatus.BAD_REQUEST, data: MutableMap<String, Any> = mutableMapOf(), response: HttpServletResponse = getResponse()){
        response.contentType = MediaType.APPLICATION_JSON_UTF8_VALUE
        response.status = status.value()
        data["status"] = status.value()
        data["timestamp"] = Date()
        data["message"] = message

        objectMapper.writeValue(response.writer, data)
    }
}
